package com.stox.ui.javafx.charting.application;

import java.util.Collection;

import javafx.scene.control.ContextMenu;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import com.stox.dto.AbstractModel;
import com.stox.dto.intf.AbstractModelNavigable;
import com.stox.ui.javafx.charting.widget.ChartingContextMenu;
import com.stox.ui.javafx.charting.widget.menu.item.ShowChartsMenuItem;

@Component
public class ChartingMediator implements BeanPostProcessor {

	@Autowired
	private ApplicationContext applicationContext;
	
	@Override
	public Object postProcessBeforeInitialization(Object bean, String beanName)
			throws BeansException {
		return bean;
	}

	@Override
	@SuppressWarnings("unchecked")
	public Object postProcessAfterInitialization(Object bean, String beanName)
			throws BeansException {
		if(bean instanceof ContextMenu && bean instanceof AbstractModelNavigable && !(bean instanceof ChartingContextMenu)){
			ContextMenu contextMenu = (ContextMenu)bean;
			ShowChartsMenuItem item = applicationContext.getBean(ShowChartsMenuItem.class);
			item.setAbstractModelCollectionProvider((AbstractModelNavigable<? extends Collection<AbstractModel>>)bean);
			contextMenu.getItems().add(item);
		}
		
		return bean;
	}

}
